﻿package net.wangit.adm.user;

import net.wangit.User;
import net.wangit.context.ActionContext;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.support.action.TransactionAction;
import net.wangit.user.AdminUser;
import net.wangit.util.Checker;

public class UserAuthAction extends TransactionAction {

	private static final String SQL_SUPERUSER_CLEAR_GROUP = "delete from AUSERGROUP where userid=?";
	private static final String SQL_SUPERUSER_CLEAR_ROLE = "delete from AUSERROLE where userid=?";
	private static final String SQL_ADMINISTRATOR_CLEAR_GROUP = "delete from AUSERGROUP where userid=?  and groupid in (select groupid from AADMINGROUP where adminid=?)";
	private static final String SQL_ADMINISTRATOR_CLEAR_ROLE = "delete from AUSERROLE where userid=?  and roleid in (select roleid from AADMINROLE where adminid=?)";

	public UserAuthAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String userId = ac.getRequestParameter("user.authorization.userid");
		if (Checker.isEmpty(userId))
			return;
		User user = ac.getVisitor().getUser();
		if (user instanceof AdminUser) {
			String administratorId = user.get("adminid");
			String values[] = { userId, administratorId };
			int types[] = { 2, 2 };
			db
					.execute(
							"delete from AUSERGROUP where userid=?  and groupid in (select groupid from AADMINGROUP where adminid=?)",
							values, types);
			db
					.execute(
							"delete from AUSERROLE where userid=?  and roleid in (select roleid from AADMINROLE where adminid=?)",
							values, types);
		} else {
			db.execute("delete from AUSERGROUP where userid=?", userId, 2);
			db.execute("delete from AUSERROLE where userid=?", userId, 2);
		}
		String checks[] = ac.getRequestParameters("a.groups");
		if (!Checker.isEmpty(checks)) {
			Table table = new Table("adm", "AUSERGROUP");
			for (int i = 0; i < checks.length; i++) {
				ColumnRow row = table.addInsertRow();
				row.set("userid", userId);
				row.set("groupid", checks[i]);
			}

			db.save(table);
		}
		checks = ac.getRequestParameters("a.roles");
		if (!Checker.isEmpty(checks)) {
			Table table = new Table("adm", "AUSERROLE");
			for (int i = 0; i < checks.length; i++) {
				ColumnRow row = table.addInsertRow();
				row.set("userid", userId);
				row.set("roleid", checks[i]);
				row.set("hold", 1);
			}

			db.save(table);
		}
		checks = ac.getRequestParameters("a.repellentroles");
		if (!Checker.isEmpty(checks)) {
			Table table = new Table("adm", "AUSERROLE");
			for (int i = 0; i < checks.length; i++) {
				ColumnRow row = table.addInsertRow();
				row.set("userid", userId);
				row.set("roleid", checks[i]);
				row.set("hold", 0);
			}

			db.save(table);
		}
	}
}
